/*
	jGrouse framework
	Copyright 2007 by Denis Riabtchik 
	All rights reserved.
	
	Licensed under modified BSD license. See license.txt for details
*/
/**
	Simple implementation of logging
	@file log.js
*/

/**
	@struct jgrouse.log
*/
jgrouse.log = 
{
	NONE : 0,
	ERROR : 1,
	WARN : 2,
	INFO : 3,
	DEBUG : 4,
	ALL : 99,
	
	_map : {'NONE' : 0, 'ERROR' : 1, 'WARN' : 2, 'INFO' : 3, 'DEBUG' : 4, 'ALL': 99},
	_revMap : ['N/A', 'ERROR', 'WARN', 'INFO', 'DEBUG'],
	
	_level : jgrouse_config.logLevel? jgrouse_config.logLevel : 0,
	
	_handlers : {},
	
	_mapLevel : function(level)
	{
		if (typeof level == 'string')
		{
			level = this._map[level.toUpperCase(level)] || 0;
		}
		return level;
	},
	
	strLevel : function(level)
	{
		if (typeof level == 'number')
		{
			return this._revMap[level];
		}
		return level;
	},
	
	log : function(level, message, sender)
	{
		level = this._mapLevel(level);
		if (level <= jgrouse.log._level)
		{
			jgrouse.forEach(jgrouse.log._handlers, function(handler, handlerName)
			{
				if (handlerName == '.' || (sender && sender.length >= handlerName.length && 
					sender.indexOf(handlerName) == 0 && (sender.length == handlerName.length || sender.length[handler.length - 1] == '.')))
				{
					handler.log(level, message, sender);
				}
			});
		}
	},
	
	error : function(message, sender)
	{
		this.log(this.ERROR, message, sender);
	},
	
	warn : function(message, sender)
	{
		this.log(this.WARN, message, sender);
	},
	
	info : function(message, sender)
	{
		this.log(this.INFO, message, sender);
	},
	
	debug : function(message, sender)
	{
		this.log(this.DEBUG, message, sender);
	},
	
	setLevel : function(level)
	{
		level = this._mapLevel(level);
		jgrouse.log._level = level;
	},
	
	addHandler : function(logger, loggerName)
	{
		if (!loggerName)
		{
			loggerName = '.';
		}
		jgrouse.log._handlers[loggerName] = logger;
	}
}

jgrouse.log.setLevel(jgrouse.log._level);


if (!jgrouse.logHandlers)
{
	jgrouse.logHandlers = {};
}

jgrouse.logHandlers.ConsoleLog = function()
{
	return this;
}

jgrouse.logHandlers.ConsoleLog.prototype = 
{
	log : function(level, message, sender)
	{
		if (typeof console != 'undefined')
		{
			var msg = sender? sender : '';
			msg += '[' + jgrouse.log.strLevel(level) + ']:' + message;
			console.log(msg);
		}
	}
}

if (jgrouse_config.initLogs)
{
	jgrouse_config.initLogs();
}
